<template>
  <div class="graph-chart-wrapper">
    <div id="graph-chart" :style="{ width: '100%', height: '100%' }"></div>
  </div>
</template>

<script lang="ts" setup>
import * as echarts from 'echarts/core';
import { EChartsOption, GraphSeriesOption } from 'echarts';
import { TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components';
import { GraphChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';

const props = defineProps({
  eChartsOption: {
    type: Object as PropType<EChartsOption>,
    default: () => {
      return {};
    },
  },
  graphSeriesOption: {
    type: Object as PropType<GraphSeriesOption>,
    required: true,
  },
});
const { eChartsOption, graphSeriesOption } = toRefs(props);

const currentChart = ref();

onMounted(() => {
  const chartDom = document.getElementById('graph-chart');
  echarts.use([TitleComponent, TooltipComponent, LegendComponent, GraphChart, CanvasRenderer]);
  currentChart.value = echarts.init(chartDom);
  updateChart(eChartsOption.value, graphSeriesOption.value);
});

watch(
  [eChartsOption, graphSeriesOption],
  ([eChartsOption_, graphSeriesOption_]) => {
    updateChart(eChartsOption_, graphSeriesOption_);
  },
  { deep: true },
);

const updateChart = (eChartsOption_: EChartsOption, graphSeriesOption_: GraphSeriesOption) => {
  const graphChart_ = currentChart.value;
  if (graphChart_) {
    graphChart_.setOption({
      ...eChartsOption_,
      legend: [
        {
          data: (graphSeriesOption_.categories ?? []).map(function (a) {
            return a.name;
          }),
        },
      ],
      series: [graphSeriesOption_],
    });
  }
};
</script>

<style scoped>
.graph-chart-wrapper {
  width: 100%;
  height: 100%;
}
</style>
